package org.hertsig.magiccardmarket;

import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import lombok.AllArgsConstructor;

import org.apache.http.HttpResponse;

/**
 * Iterable to lazily iterate over a paged list of results returned from the API.
 * Each time {@link #iterator()} is called, a new iterator will be created, and each iterator will do its own queries.
 * In other words, iterating over this multiple times will repeat the queries each time.
 */
@AllArgsConstructor
public final class PartialContentIterable<T> implements Iterable<T> {
	private final Class<? extends Iterable<T>> type;
	private final Function<Integer, HttpResponse> producer;
	
	/**
	 * @see PartialContentIterator
	 */
	@Override
	public PartialContentIterator<T> iterator() {
		return new PartialContentIterator<T>(type) {
			@Override
			HttpResponse openConnection(int nextStartIndex) {
				return producer.apply(nextStartIndex);
			}
		};
	}
	
	public Stream<T> stream(boolean parallel) {
		return StreamSupport.stream(spliterator(), parallel);
	}
}
